package cn.ekuma.epos.datalogic.businesslogic;

import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.openbravo.bean.erp.Order;
import com.openbravo.bean.erp.ordercalc.OrderCalcItem;
import com.openbravo.bean.erp.ordercalc.OrderTypeCalcConfig;
import com.openbravo.data.basic.BasicException;
import com.openbravo.pos.util.RoundUtils;

import net.xeoh.plugins.base.PluginManager;
import net.xeoh.plugins.base.util.PluginManagerUtil;
import cn.ekuma.epos.datalogic.businesslogic.ordercalc.I_OrderCalc;

public class OrderCalcManager {
	
	private Map<String,I_OrderCalc> processMap=new HashMap<String,I_OrderCalc>();
	
	private List<OrderTypeCalcConfig> configs;
	

	public void init(PluginManager pmf) {
		PluginManagerUtil pmu = new PluginManagerUtil(pmf);
        
    	Collection<I_OrderCalc> plugins1 = pmu.getPlugins(I_OrderCalc.class);
    	for(I_OrderCalc orderCalc:plugins1){
    		processMap.put(orderCalc.getOrderCalcId(), orderCalc);
    	}
	}
	
	public void calcOrder(Order order) throws BasicException{
		double totalExtendPrice=0;
		List<OrderCalcItem> ret=new ArrayList<OrderCalcItem>();
		for(OrderTypeCalcConfig config:getOrderTypeConfig(order.getDefineType().getId())){
			I_OrderCalc calc=processMap.get(config.getOrderCalcId());
			if(calc!=null){
				ret.addAll(calc.calcOrder(config, order));
			}
		}
		for(OrderCalcItem calcItem:ret)
			totalExtendPrice=RoundUtils.add(totalExtendPrice,calcItem.getTotalPrice());
		order.setTotalExtendPrice(totalExtendPrice);
		order.setCalcItems(ret);
	}
	
	private List<OrderTypeCalcConfig> getOrderTypeConfig(String orderTypeId){
		List<OrderTypeCalcConfig> ret=new ArrayList<OrderTypeCalcConfig>();
		for(OrderTypeCalcConfig config:configs)
			if(config.isAbled()||orderTypeId.equalsIgnoreCase(config.getOrderTypeId()))
				ret.add(config);
		return ret;
	}

	public List<OrderTypeCalcConfig> getConfigs() {
		return configs;
	}

	public void setConfigs(List<OrderTypeCalcConfig> configs) {
		this.configs = configs;
	}
}
